# cookies 两种方式
# url 方式
# cookies方式
# https://www.douban.com/misc/captcha?id=mH5bXuTHE2CQIFdsvSE5Yf5K:en&size=s
# mH5bXuTHE2CQIFdsvSE5Yf5K:en
import requests
import re
#一个随机生成user-agent的工具
from fake_useragent import UserAgent

s=requests.session()

ua=UserAgent()
url = 'https://accounts.douban.com/login'
data={
    'source':'None',
    'form_email':'15673129465',
    'form_password':'sunsunsun520',
    'captcha-solution':'',
    'user_login':u'登陆',
    'captcha-id':''
}
headers = {
    'User-Agent': ua.random
}

#获取代理ip
response = requests.get('http://192.168.0.132:5000/get')
proxies1 = {'http':'http://'+response.text,'https':'http://'+response.text}
print(proxies1)

#获取验证图片的唯一id标识
response=requests.get(url=url,headers=headers,proxies=proxies1)
#如果获取不到验证码的id，表示当前登录不需要添加验证码，采取第二种data表单的方式
try:
    captcha_id = re.findall('<input type="hidden" name="captcha-id" value="(.*)"/>',response.text)[0]
except Exception:
    print('hi')
    data = {
        'source': 'index_nav',
        'form_email': '15673129465',
        'redir':'https://www.douban.com/',
        'form_password': 'sunsunsun520',
        'user_login': u'登陆',
    }
    response = s.post(url=url, data=data, headers=headers)
    print(response.text)
    print(s.cookies)
    exit()


print(captcha_id)
#请求图片，下载到本地
captcha_url='https://www.douban.com/misc/captcha?id={}&size=s'.format(captcha_id)
response=requests.get(captcha_url)
with open('captcha.jpg','wb') as filee:
    filee.write(response.content)
captcha_str=input("请输入验证码:")

data['captcha-id']=captcha_id
data['captcha-solution']=captcha_str
response=s.post(url=url,data=data,headers=headers)
print(response.text)
print(s.cookies)